package cn.xinfei.xdecision.common.utils.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public final class PageUtils {

    public static final int GROUP_SIZE = 200;

    private PageUtils() {
    }

    /**
     * 内存分页
     *
     * @param list     待分页数据源
     * @param pageNum  入参分页页码
     * @param pageSize 入参分页数量
     */
    public static <T> List<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 记录总数
        Integer count = list.size();
        // 页数
        int pageCount;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        // 开始索引
        int fromIndex = (pageNum - 1) * pageSize;
        // 结束索引
        int toIndex;
        //分页时当起始index大于list长度时，直接返回null
        if (fromIndex > (list.size() - 1)) {
            return Collections.emptyList();
        }
        if (!pageNum.equals(pageCount)) {
            toIndex = fromIndex + pageSize;
        } else {
            toIndex = count;
        }
        return list.subList(fromIndex, toIndex);
    }

    /**
     * 拆成指定大小的组，拆后的分组数由程序计算
     */
    public static <T> List<List<T>> splitList(List<T> sourceList, int groupSize) {
        //结果
        List<List<T>> resultList = new LinkedList<>();
        //空判断
        if (CollectionUtils.isEmpty(sourceList) || groupSize <= 0) {
            resultList.add(sourceList);
            return resultList;
        }
        //分组计算
        int groups = (sourceList.size() - 1) / groupSize + 1;
        //循环处理
        for (int i = 0; i < groups; i++) {
            int start = i * groupSize;
            int end = Math.min((i + 1) * groupSize, sourceList.size());
            resultList.add(sourceList.subList(start, end));
        }
        return resultList;
    }
}
